package com.iceframework.core.base;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iceframework.core.entity.Result;

public class BaseController {
	
	protected final Log logger = LogFactory.getLog(getClass());

    @InitBinder  
    public void initBinder(WebDataBinder binder) {  
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
	    dateFormat.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值  
    }
    
	/**
	 * 异常处理(包括异步请求)
	 * 
	 * @param error
	 * @param request
	 * @param response
	 * @return
	 */
	@ExceptionHandler
	@ResponseBody
	public Result doException(Throwable error, HttpServletRequest request, HttpServletResponse response) {
		String log = error.getMessage();
		if(log == null){
			log = "";
		}
		logger.error("*************Exception***************");
		logger.error("Exception："+error.getMessage());
		error.printStackTrace();
		logger.error("*************************************");
		return Result.exception().setMsg(log);
	}
	
}
